from rest_framework import serializers
from .models import *
from django.contrib.auth.hashers import make_password
import re


class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

    def validate_phone(self, value):
        print("-----phone-----:{}".format(value))

        if not re.match("^1[35789]\d{9}$", value):
            raise serializers.ValidationError("手机号格式错误", code=401)
        return value

    def validate_username(self, value):
        print("-----username-----:{}".format(value))
        return value

    def create(self, validated_data):
        validated_data["password"] = make_password(validated_data["password"])
        print("密文长度:{}".format(len(validated_data["password"])))
        instance = User.objects.create(**validated_data)
        return instance
